<template>
  <div class="booking-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>预约管理</span>
          <el-button type="primary" @click="$router.push('/booking/form')">
            <el-icon><Plus /></el-icon>
            新建预约
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
            v-model="searchForm.roomName"
            placeholder="会议室名称"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.userName"
            placeholder="预约人"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.status"
            placeholder="预约状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>

      <!-- 预约列表 -->
      <el-table :data="filteredBookings" style="width: 100%">
        <el-table-column prop="roomName" label="会议室" width="120" />
        <el-table-column prop="userName" label="预约人" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="duration" label="时长" width="80">
          <template #default="scope">
            {{ calculateDuration(scope.row.startTime, scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="用途" />
        <el-table-column prop="attendees" label="参会人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
              :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled'"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleCancel(scope.row)"
              :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled'"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleConfirm(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="预约详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会议室">{{ currentBooking.roomName }}</el-descriptions-item>
        <el-descriptions-item label="预约人">{{ currentBooking.userName }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentBooking.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentBooking.endTime }}</el-descriptions-item>
        <el-descriptions-item label="时长">{{ calculateDuration(currentBooking.startTime, currentBooking.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="参会人数">{{ currentBooking.attendees }}人</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentBooking.status)">
            {{ getStatusText(currentBooking.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentBooking.createTime }}</el-descriptions-item>
        <el-descriptions-item label="用途" :span="2">{{ currentBooking.purpose }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentBooking.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 预约数据
const bookings = ref([
  {
    id: 1,
    roomName: '会议室A',
    userName: '张三',
    startTime: '2024-01-15 09:00',
    endTime: '2024-01-15 11:00',
    purpose: '项目讨论会议',
    attendees: 8,
    status: 'confirmed',
    createTime: '2024-01-14 14:30',
    remark: '需要准备投影仪'
  },
  {
    id: 2,
    roomName: '会议室B',
    userName: '李四',
    startTime: '2024-01-15 14:00',
    endTime: '2024-01-15 16:00',
    purpose: '客户洽谈',
    attendees: 5,
    status: 'pending',
    createTime: '2024-01-14 16:20',
    remark: ''
  },
  {
    id: 3,
    roomName: '会议室C',
    userName: '王五',
    startTime: '2024-01-15 10:00',
    endTime: '2024-01-15 12:00',
    purpose: '团队建设',
    attendees: 12,
    status: 'completed',
    createTime: '2024-01-14 10:15',
    remark: '需要音响设备'
  },
  {
    id: 4,
    roomName: '会议室A',
    userName: '赵六',
    startTime: '2024-01-16 09:00',
    endTime: '2024-01-16 10:30',
    purpose: '部门例会',
    attendees: 15,
    status: 'cancelled',
    createTime: '2024-01-14 09:45',
    remark: ''
  }
])

// 搜索表单
const searchForm = reactive({
  roomName: '',
  userName: '',
  status: '',
  date: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(bookings.value.length)

// 对话框
const showDetailDialog = ref(false)
const currentBooking = ref({})

// 过滤后的预约列表
const filteredBookings = computed(() => {
  let result = bookings.value

  if (searchForm.roomName) {
    result = result.filter(booking =>
      booking.roomName.toLowerCase().includes(searchForm.roomName.toLowerCase())
    )
  }

  if (searchForm.userName) {
    result = result.filter(booking =>
      booking.userName.toLowerCase().includes(searchForm.userName.toLowerCase())
    )
  }

  if (searchForm.status) {
    result = result.filter(booking => booking.status === searchForm.status)
  }

  if (searchForm.date) {
    result = result.filter(booking =>
      booking.startTime.startsWith(searchForm.date)
    )
  }

  return result
})

// 计算时长
const calculateDuration = (startTime: string, endTime: string) => {
  const start = dayjs(startTime)
  const end = dayjs(endTime)
  const diff = end.diff(start, 'minute')
  const hours = Math.floor(diff / 60)
  const minutes = diff % 60

  if (hours > 0) {
    return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`
  } else {
    return `${minutes}分钟`
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    confirmed: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.roomName = ''
  searchForm.userName = ''
  searchForm.status = ''
  searchForm.date = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 编辑预约
const handleEdit = (row: any) => {
  // 跳转到编辑页面，传递预约ID
  ElMessage.info('跳转到编辑页面')
}

// 取消预约
const handleCancel = (row: any) => {
  ElMessageBox.confirm(
    `确定要取消预约"${row.roomName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = bookings.value.findIndex(booking => booking.id === row.id)
    if (index > -1) {
      bookings.value[index].status = 'cancelled'
      ElMessage.success('取消成功')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 确认预约
const handleConfirm = (row: any) => {
  ElMessageBox.confirm(
    `确定要确认预约"${row.roomName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    const index = bookings.value.findIndex(booking => booking.id === row.id)
    if (index > -1) {
      bookings.value[index].status = 'confirmed'
      ElMessage.success('确认成功')
    }
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped lang="scss">
.booking-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>